import { Provide } from '@midwayjs/decorator';
// import { BaseService } from 'midwayjs-cool-core';

import { InjectEntityModel, useEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { studentEntity } from '../entity/student';
import { loeeBaseService } from '../../../comservice/loeeBaseService';
import { financeEntity } from '../../finance/entity/finance';

/**
 * 描述
 */
@Provide()
export class StudentService extends loeeBaseService {
  @InjectEntityModel(studentEntity)
  studentEntity: Repository<studentEntity>;

  @InjectEntityModel(financeEntity)
  financeEntity: Repository<financeEntity>;
  /**
   * 重写删除方法设置为逻辑删除
   */
  //  async add(param) {
  //     if (!this.entity)
  //         throw new validate_1.CoolValidateException(global_1.ERRINFO.NOENTITY);
  //     await this.addOrUpdate(param);
  //     await this.modifyAfter(param);
  //     return {
  //         id: param.id
  //     };
  // }

  async add(param: any) {
    const res = await useEntityModel(studentEntity).findOne({
      order: {
        student_id: "DESC"
      }
    })
    let num: any
    let newStudnetId: String
    console.log(res, '--------');

    // 设置学号自动生成
    if (res) {
      num = res.student_id.match(/\d+/g)
      newStudnetId = prefixZero(parseInt(num[0]) + 1, 4);
    } else {
      newStudnetId = "0001"
    }

    param.student_id = "KC_" + newStudnetId
    const studentsObj: any = await super.add(param);
    // console.log(studentsObj,'++++=');

    // console.log(param,'--------');
    const financeInfo: any = {}
    financeInfo.money = param.money
    financeInfo.common_num = param.common_num
    financeInfo.special_num = param.special_num
    financeInfo.into_date = param.into_date
    financeInfo.discount = param.discount
    financeInfo.note = param.financeNote
    financeInfo.student = studentsObj.id
    await this.financeEntity.save(financeInfo)
    // const financeObj = await this.financeEntity.findOne({student:infoObj.id})
    return studentsObj
    // await this.modifyAfter(param);
  }

  /**
     * 重写info方法
     * @param id ID
     * @param infoIgnoreProperty 忽略返回属性
     */
  async info(id, infoIgnoreProperty) {
    const infoObj = await super.info(id, infoIgnoreProperty)
    const financeObj = await this.financeEntity.findOne({ student: infoObj.id })
    if (financeObj) {
      infoObj.finance = { ...financeObj }
      infoObj.money = financeObj.money
      infoObj.into_date = financeObj.into_date
      infoObj.common_num = financeObj.common_num
      infoObj.special_num = financeObj.special_num
      infoObj.discount = financeObj.discount
      infoObj.financeNote = financeObj.note
    }
    return infoObj
  }

  /**
     * 重写分页查询
     * @param query
     */
  async page(query) {
    const { keyWord, status } = query;

    // query.order = 'sort'
    // query.sort = 'asc'
    // const permsDepartmentArr = await this.baseSysPermsService.departmentIds(
    //   this.ctx.admin.userId
    // ); // 部门权限
    let order = query.order
    let sort = query.sort
    let orderList = []
    switch (order) {
      case 'special_rest_num':
        orderList.push('special_rest_num '+sort)
        break;
      case 'common_rest_num':
        orderList.push('common_rest_num '+sort)
        break;
      default:
        orderList.push('common_rest_num ASC')
        break;
    }
    
    
    let sql = `
      SELECT distinct
          a.id,a.name,a.student_id,a.gender,a.birthday,a.phone,a.status,a.into_date,a.stop_time,a.note,a.createTime,a.updateTime,a.isDelete,
          (ifnull(b.common_nums,0) - ifnull(c.common_use_nums,0)) as common_rest_num,b.common_nums,c.common_use_nums,(ifnull(b.special_nums,0) - ifnull(c.special_use_nums,0)) as special_rest_num,b.special_nums,c.special_use_nums
      FROM
          student a
          LEFT JOIN (select student,sum(common_num) as common_nums,sum(special_num) as special_nums from finance where isDelete=false group by student) b ON a.id = b.student
          LEFT JOIN (select a.student,sum(a.common_use_num) as common_use_nums,sum(a.special_use_num) as special_use_nums 
          from student_class_detail a 
          left join class_teaching b
          on a.class_teaching = b.id
          where a.isLeave=false and a.isDelete=false and b.isDelete = false
          group by a.student) c ON a.id = c.student
      WHERE 1 = 1 and a.isDelete = false
      ${this.setSql(status, 'and a.status = ?', [status])}
      ${this.setSql(keyWord, 'and (a.name LIKE ? or a.student_id LIKE ?)', [
      `%${keyWord}%`,
      `%${keyWord}%`,
    ])}
      GROUP BY a.id
      ORDER BY 
      `;
      orderList.push('a.updateTime DESC')
      sql = sql + orderList.toString();
      
    return this.sqlRenderPage(sql, query,true);
  }
}

function prefixZero(n: number, m: number) {
  var _a = (Array(m).join("0") + n).slice(-m);
  return _a;
}